<template>
  <van-nav-bar
    title="地址"
    left-text="返回"
    left-arrow
    @click-left="$router.go(-1)"
  />
  <!-- 地址列表 -->
  <van-address-list
    v-model="chosenAddressId"
    :list="list"
    disabled-text="以下地址超出配送范围"
    default-tag-text="默认"
    @add="onAdd"
    @edit="onEdit"
  />
  <!-- 编辑地址 -->
  <van-action-sheet v-model:show="isshowadd">
    <van-address-edit
      :area-list="areaList"
      :show-delete="showdelete"
      :address-info="addressInfo"
      show-postal
      show-set-default
      show-search-result
      :search-result="searchResult"
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="onSave"
      @delete="onDelete"
    />
  </van-action-sheet>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import type { Ref } from "vue";
import {
  addAddress,
  delAddress,
  addressList,
  addressUpdate,
  defaultAddress,
} from "../api/api";
import { useUserInfoStore } from "../stores/userInfo";
import { areaList } from "@vant/area-data";
import type { AddressListAddress } from "vant";

const store = useUserInfoStore();
const isshowadd = ref(false);
const chosenAddressId = ref(1);
const addressInfo = ref({});
const list = ref<AddressListAddress[]>([]);
const searchResult = ref([]);
const areaCode = ref<string>("");
const addressid = ref<string>("");
const showdelete = ref<boolean>(false);

const getListdata = async () => {
  const res = await addressList({
    userid: store.userId,
  });
  if (res.data) {
    list.value = res.data;
    list.value.forEach((item: any, index: number) => {
      item.id = index;
      item.address =
        item.province + item.city + item.country + item.addressDetail;
    });
  }
};

// 新增地址
const onAdd = () => {
  // 设置地址信息初始值为空
  addressInfo.value = [];
  isshowadd.value = true;
  showdelete.value = false;
};
// 保存按钮
const onSave = async (content: any) => {
  const res = await addAddress({
    userid: store.userId,
    name: content.name,
    tel: content.tel,
    province: content.province,
    city: content.city,
    county: content.county,
    addressDetail: content.addressDetail,
    isDefault: content.isDefault,
  });
  if (res.data) {
    areaCode.value = content.areaCode;
    isshowadd.value = false;
  }
  getListdata();
};

// 编辑地址
const onEdit = (item: any, index: number) => {
  // 显示编辑地址面板
  isshowadd.value = true;
  // 显示删除按钮
  showdelete.value = true;
  // 设置信息初始值
  addressInfo.value = {
    id: item.userId,
    name: item.name,
    tel: item.tel,
    province: item.province,
    city: item.city,
    county: item.county,
    addressDetail: item.addressDetail,
  };
  addressid.value = item.addressid;
};

// 点击删除按钮
const onDelete = async (content: any) => {
  const res = await delAddress({
    addressid: addressid.value,
  });
  if (res.data) {
    console.log("删除地址");
    isshowadd.value = false;
  }
  getListdata();
};
onMounted(() => {
  getListdata();
});
</script>

<style lang="scss" scoped></style>
